package com.I9lou.se.lurker.facet.index.support;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.facet.index.CategoryDocumentBuilder;
import org.apache.lucene.facet.taxonomy.CategoryPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.I9lou.se.lurker.facet.index.DocumentFacetBuilder;
import com.I9lou.se.lurker.facet.index.TaxonomyWriterFactory;

public class SimpleDocumentFacetBuilder implements DocumentFacetBuilder {

	private static final Logger LOG = LoggerFactory.getLogger(SimpleDocumentFacetBuilder.class);
	
	private TaxonomyWriterFactory taxonomyWriterFactory;
	
	public SimpleDocumentFacetBuilder(TaxonomyWriterFactory taxonomyWriterFactory){
		this.taxonomyWriterFactory = taxonomyWriterFactory;
	}
	
	@Override
	public void build(Document document, Collection<List<String>> categroiesList) {
		try {
			if( categroiesList == null || categroiesList.isEmpty() ){
				throw new IllegalArgumentException("Illegal Argument of categroiesList, categroiesList is empty");
			}
			int appId = Integer.parseInt(categroiesList.iterator().next().get(0));
			CategoryDocumentBuilder categoryDocumentBuilder =
					new CategoryDocumentBuilder(taxonomyWriterFactory.getTaxonomyWriter().get(appId));
			List<CategoryPath> categoriesPath = extractCategroiesPath(categroiesList);
			categoryDocumentBuilder.setCategoryPaths(categoriesPath);
			categoryDocumentBuilder.build(document);
		} catch (IOException e) {
			LOG.error("Create CategoryDocumentBuilder faild", e);
		}
	}
	
	private List<CategoryPath> extractCategroiesPath(Collection<List<String>> categroiesList) {
		List<CategoryPath> categoriesPaths = new ArrayList<CategoryPath>();
		for( List<String> categroyList : categroiesList ){
			categoriesPaths.add(new CategoryPath(categroyList.toArray(new String[categroyList.size()])));
		}
		return categoriesPaths;
	}
}